package unit2;

import java.io.IOException;

import unit2.authorization.Authorization;
import unit2.creater.CreaterUsers;
import unit2.db.Users;
import unit2.user.User;

public class TestController {
	private Test ourTest;
	private Authorization authorization;
	private Users users;
	private User currentUser;
	
	public void start() throws ClassNotFoundException, IOException{
		currentUser=authorization.initUser(users);
		users=CreaterUsers.readUsersFromFile();
		doTest();	
	}

	private void nextQuestion(){
		ourTest.nextQuestion();
	}
	
	public TestController() throws ClassNotFoundException, IOException{
		authorization=new Authorization();
		users=new Users();
	}
	
	private void previousQuestion(){
		ourTest.previousQuestion();
	}
		
	private void save() throws IOException{
		this.currentUser.saveHistory(new UserHistory(this.ourTest));
		this.users.saveUser(this.currentUser);
		CreaterUsers.writeUsersInFile(this.users);
	}
	
	private void cleanTest() throws IOException{		
		this.users.saveFinishScore(this.currentUser.getName(), this.ourTest.sumScore() );
		this.users.cleanTest(this.currentUser);
		CreaterUsers.writeUsersInFile(this.users);
	}
	
	private void showScoreCurrentUser(){
		ourTest.showScore();
	}
	
	private boolean  movements() throws IOException{
		
		switch (this.currentUser.action()) {
			case "n":  
				nextQuestion();
				break;
			case "p":  
				previousQuestion();
				break;
			case "s":  
				save();
				break;
			case "admin-root":
				admin();
				break;
			case "score":
				showScoreCurrentUser();
				cleanTest();
				break;
			case "e": 
				return false;
		
			default:
				System.out.println("bad input");
				break;
		}
		
		return true;	
	}
	
	private void admin(){
		this.users.showScore();
	}
	
	//TO DO
	private void doTest() throws IOException{
		if(currentUser.getUserHistory()==null){
			ourTest = new Test();			 
			while(movements()){
			}
		}
		
		else{
			ourTest= currentUser.getUserHistory().getTest();
			while(movements()){
			}
		}
	}

}
